package com.hsy.leancloudchat.chat

import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.leancloud.im.v2.LCIMClient
import cn.leancloud.im.v2.LCIMConversation
import cn.leancloud.im.v2.LCIMMessage
import com.hsy.leancloudchat.CustomIMEventHandler
import com.hsy.leancloudchat.LeanCloudHelper
import com.hsy.leancloudchat.databinding.ActivityChatBinding
import com.hsy.leancloudchat.mvvmUtils.HsyActivity

class ChatActivity : HsyActivity<ActivityChatBinding, ChatViewModel>(),
    CustomIMEventHandler.IIMEventSubscriber {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        CustomIMEventHandler.subscribe(this)

        handleIntent()
        setBackClick()
        initRVChat()
        setSendClick()

        mViewModel.mConversationLiveData.observe(this) {
            LeanCloudHelper.mLastPickConversation = it
            LeanCloudHelper.getInstance().getHistoryMessages(
                it, 100, mViewModel.mMessagesLiveData, this
            )
        }

        mViewModel.mMessagesLiveData.observe(this) {
            (mBinding.rvChat.adapter as ChatAdapter).apply {
                messageList = it
                if (messageList.size > 0) {
                    mBinding.rvChat.smoothScrollToPosition(messageList.size - 1)
                }
            }
        }

        mViewModel.mLastMessageLiveData.observe(this) {
            mViewModel.mMessagesLiveData.apply {
                value?.add(it)
                postValue(value)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.mConversationLiveData.let {
            if (it.value == null) return
            LeanCloudHelper.getInstance().createConversation(
                LeanCloudHelper.mCurrentClientLiveData.value!!,
                mutableListOf(it.value!!.conversationId),
                it.value!!.name,
                this
            ) {
                initInfo()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        CustomIMEventHandler.unSubscribe(this)
    }

    override fun onMessage(
        message: LCIMMessage?,
        conversation: LCIMConversation?,
        client: LCIMClient?
    ) {
        if (conversation?.conversationId == mViewModel.mConversationLiveData.value?.conversationId) {
            mViewModel.mLastMessageLiveData.postValue(message)
        }
    }

    private fun handleIntent() {
        intent.getStringExtra("conversationId")?.let {
            LeanCloudHelper.getInstance().getConversationById(
                it, mViewModel.mConversationLiveData, this
            )
        }
        intent.getStringExtra("friendUserName")?.let {
            mBinding.topName.text = it
        }
    }

    private fun initInfo() {
        // 根据 conversation加载其他属性
    }

    private fun setBackClick() {
        mBinding.topBack.setOnClickListener {
            finish()
        }
    }

    private fun initRVChat() {
        mBinding.rvChat.apply {
            adapter = ChatAdapter()
            layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        }
    }

    private fun setSendClick() {
        mBinding.imgSend.setOnClickListener {
            if (mBinding.etInput.text.toString() == "") return@setOnClickListener
            mViewModel.mConversationLiveData.value?.let { conversation ->
                LeanCloudHelper.getInstance().sendMessage(
                    conversation,
                    mBinding.etInput.text.toString(),
                    mViewModel.mLastMessageLiveData,
                    this
                )
                mBinding.etInput.setText("")
            }
        }
    }
}